package top.anydata.lifeofcode.lifesystem.conf;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.RegexRequestMatcher;
import top.anydata.lifeofcode.lifesystem.service.sys.user.IUserService;
import top.anydata.lifeofcode.lifesystem.web.filter.AppAuthenticationFilter;
import top.anydata.lifeofcode.lifesystem.web.filter.JwtAuthenticationFilter;

import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS;

/**
 * 功能描述:
 *
 * @author <a href="mailto:caingao@anydata.top">CainGao</a>
 * @version V_1.0
 * @date 2023/8/31 3:34 PM
 */
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    @Autowired
    JwtAuthenticationFilter jwtAuthenticationFilter;

    @Autowired
    AppAuthenticationFilter appAuthenticationFilter;

    @Autowired
    CustomPermissionEvaluator customPermissionEvaluator;

    private final IUserService userService;

    private final static String[] AUTH_WHITELIST = {
            "/sys/api/auth/signup",
            "/sys/api/auth/signin",
            "/sys/api/auth/captcha",
            "/favicon.ico"
    };

    private final static String[] APP_AUTH_WHITLIST = {
            "/sys/api/auth/signup",
            "/sys/api/auth/signin",
            "/sys/api/auth/captcha",
            "/favicon.ico"
    };
    @Order(1)
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.securityMatcher(RegexRequestMatcher.regexMatcher(ConstansKey.SYS_URL_PATTERN))
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests((requests) ->
                        requests
                                .requestMatchers(
                                        AUTH_WHITELIST
                                ).permitAll()
                                .requestMatchers(RegexRequestMatcher.regexMatcher(ConstansKey.SYS_URL_PATTERN))
                                .authenticated()
                )
                .sessionManagement(manager -> manager.sessionCreationPolicy(STATELESS))
                .authenticationProvider(
                        authenticationProvider()).
                addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
    @Order(2)
    @Bean
    public SecurityFilterChain appSecurityFilterChain(HttpSecurity http) throws Exception{
        http.securityMatcher(RegexRequestMatcher.regexMatcher(ConstansKey.APP_URL_PATTERN))
                .csrf(AbstractHttpConfigurer::disable)
                .addFilterBefore(appAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userService.userDetailsService());
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }

    @Bean
    public MethodSecurityExpressionHandler expressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(customPermissionEvaluator);
        return expressionHandler;
    }

}
